package com.cn.wanxi.config;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//表示拦截所有地址
public class MyFilter extends HttpFilter {

    /**
     * 判断用户是否已经登录
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
//        这里统一设置乱码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        /*
        如果直接用/*来判断用户是否已经登录，则/*表示所有的访问后台地址都拦截
        1.得到需要拦截（过滤）的地址
        2.根据地址判断是否需要登录
         */
        String path = req.getServletPath();

        String [] aa={"user","product","online"};

//        for (int i = 0; i < aa.length; i++) {
//            if(path.startsWith(aa[i])){
//
//            }
//        }
        if (path.startsWith("/back/")) {
            //        拿到session里面的值，判断是否有值即可
            String username=req.getParameter("username");
            Object sessionUsername = req.getSession().getAttribute(username);
            if (sessionUsername == null) {
//            跳转到登录页面
                resp.sendRedirect("/html/login.html");
            } else {
//            不做任何操作，直接放行
                chain.doFilter(req, resp);
            }
//        怎么来判断用户已经登录？是不是需要登录成功以后，加入一个标识符
        } else {
//            直接放行
            chain.doFilter(req, resp);
        }

    }
}
